package com.tchcn.cashier.order.fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.othershe.nicedialog.BaseNiceDialog;
import com.tchcn.cashier.order.R;
import com.tchcn.cashier.order.activity.MainActivity;
import com.tchcn.cashier.order.adapter.OrderAdapter;
import com.tchcn.cashier.order.dialog.ChooseDiscountDialog;
import com.tchcn.cashier.order.dialog.ChooseNumDialog;
import com.tchcn.library.dao.OrderModelDao;
import com.tchcn.library.model.GoodActModel;
import com.tchcn.library.model.OrderModel;
import com.tchcn.library.fragment.SDBaseFragment;
import com.tchcn.library.utils.SDNumberUtil;
import com.tchcn.library.utils.SDViewUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 点餐左侧界面
 * Created by sad on 2018/5/29.
 */

public class OrderFragment extends SDBaseFragment {

    TextView tvTime;//时间
    RecyclerView rvOrder;
    TextView tvRemarks;//备注
    LinearLayout llRemarks;//备注layout
    FrameLayout flGetOrder;//取单
    TextView tvTotalNum;//总数
    TextView tvMoneyTrue;//应付
    TextView tvMoneyMinus;//优惠
    TextView tvMoneyLast;//实付
    TextView tvGuide;//选择桌台开始点餐
    TextView tvClear; //清空
    TextView tvHangOrder;//挂单
    TextView tvAddGood;//点菜
    Button btnSettle;//结账

    MainActivity activity;

    OrderAdapter orderAdapter;
    //已点
    List<GoodActModel> goodLists = new ArrayList<>();

    private String remarksId ="";

    private static OrderFragment fragment;

    OrderModel orderModel;

    private int totalNumber = 0;//总数量
    private double actualMoney = 0.00;//实际价格
    private double totalMoney = 0.00;//实际价格
    private double freeMoney = 0.00;//优惠价格

    public static OrderFragment getInstance(){
        if(fragment == null){
            fragment = new OrderFragment();
        }
        return fragment;
    }

    public static OrderFragment newInstance(OrderModel orderModel) {
        fragment = new OrderFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("order",orderModel);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int onCreateContentView() {
        return R.layout.frag_order;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        initView(rootView);
        return rootView;
    }

    private void initView(final View v) {
        activity = (MainActivity) getActivity();
        if(getArguments()!=null){
            if(getArguments().getSerializable("order")!=null)
                orderModel = (OrderModel) getArguments().getSerializable("order");
        }
        rvOrder = (RecyclerView) v.findViewById(R.id.rv_order);
        tvClear = (TextView) v.findViewById(R.id.tv_clear);
        tvGuide = (TextView) v.findViewById(R.id.tv_guide);
        flGetOrder = (FrameLayout) v.findViewById(R.id.fl_get_order);
        tvTime = (TextView) v.findViewById(R.id.tv_time);
        tvGuide = (TextView) v.findViewById(R.id.tv_guide);
        btnSettle = (Button) v.findViewById(R.id.btn_settle);
        tvRemarks = (TextView) v.findViewById(R.id.tv_remarks);
        tvMoneyLast = (TextView) v.findViewById(R.id.tv_money_last);
        tvMoneyTrue = (TextView) v.findViewById(R.id.tv_money_true);
        tvMoneyMinus = (TextView) v.findViewById(R.id.tv_money_minus);
        tvTotalNum = (TextView) v.findViewById(R.id.tv_total_num);
        tvHangOrder = (TextView) v.findViewById(R.id.tv_hang_order);
        tvAddGood = (TextView) v.findViewById(R.id.tv_add_good);
        llRemarks = (LinearLayout) v.findViewById(R.id.ll_remarks);
        llRemarks.setOnClickListener(this);
        //清空
        tvClear.setOnClickListener(this);
        tvHangOrder.setOnClickListener(this);
        tvAddGood.setOnClickListener(this);
        flGetOrder.setOnClickListener(this);
        btnSettle.setOnClickListener(this);
        orderAdapter = new OrderAdapter(goodLists);
        orderAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(orderAdapter.getSelectNum() == position)
                    orderAdapter.setSelectNum(-1);
                else
                    orderAdapter.setSelectNum(position);
            }
        });
        orderAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final GoodActModel actModel = orderAdapter.getData().get(position);
                //点加号操作
                if (view.getId() == R.id.iv_add) {
                    actModel.setCarNum(actModel.getCarNum() + 1);
                    activity.notifyGoodFragment(actModel, true);
                    updateAmountPrice();
                } else if (view.getId() == R.id.iv_sub) {  //点减号操作
                    actModel.setCarNum(actModel.getCarNum() - 1);
                    if (actModel.getCarNum() == 0)
                        goodLists.remove(position);
                    activity.notifyGoodFragment(actModel, false);

                    updateAmountPrice();
                }else if(view.getId() == R.id.btn_free){
                    actModel.setFree(1);
                    updateAmountPrice();
                }else if(view.getId() == R.id.tv_discount){
                    final ChooseDiscountDialog discountDialog = ChooseDiscountDialog.newInstance();
                    discountDialog.setConvertListener(new ChooseNumDialog.OnDialogClickListener(){
                        @Override
                        public void onItemClick(View view, BaseNiceDialog dialog) {
                            if(view.getId() == R.id.tv_commit){
                                double discount = discountDialog.getNum();
                                actModel.setDiscount(discount);
                                dialog.dismiss();
                                updateAmountPrice();
                            }
                        }
                    })
                            .setWidth(SDViewUtil.px2dp(568))
                            .show(activity.getSupportFragmentManager());
                }



            }
        });
        orderAdapter.bindToRecyclerView(rvOrder);
        rvOrder.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvOrder.setNestedScrollingEnabled(false);


        List<OrderModel> orderModels = OrderModelDao.queryAllHangingOrder();
        if(orderModels != null){
            if(orderModels.size() > 0){
                flGetOrder.setVisibility(View.VISIBLE);
            }
        }

        if(orderModel!=null){
            tvGuide.setVisibility(View.GONE);
            tvHangOrder.setVisibility(View.GONE);
            tvAddGood.setVisibility(View.VISIBLE);
            tvTime.setText(orderModel.getPlaceOrderTime());
            goodLists.addAll(orderModel.getGoodList());
            updateAmountPrice();
        }else {
            tvGuide.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
            int i = v.getId();
            if (i == R.id.ll_remarks) {//备注
                if (!OrderRemarkFragment.getInstance().isAdded()) {
                    FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
                    fragmentTransaction.add(R.id.fl_container_right, OrderRemarkFragment.getInstance());
                    fragmentTransaction.commitAllowingStateLoss();
                } else {
                    FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
                    fragmentTransaction.remove(OrderRemarkFragment.getInstance());
                    fragmentTransaction.commitAllowingStateLoss();
                }
            } else if (i == R.id.tv_clear) {//清空
                goodLists.clear();
                orderAdapter.notifyDataSetChanged();
                orderAdapter.setSelectNum(-1);
                activity.clearGood();
                updateAmountPrice();
            } else if (i == R.id.tv_hang_order) {//挂单
                tvAddGood.setVisibility(View.VISIBLE);
                tvHangOrder.setVisibility(View.GONE);
                flGetOrder.setVisibility(View.VISIBLE);

                OrderModel orderModel = new OrderModel();
                List<GoodActModel> goodActModels = new ArrayList<>();
                goodActModels.addAll(goodLists);
                orderModel.setGoodList(goodActModels);
                SimpleDateFormat simpleDateFormat =new SimpleDateFormat("HH:mm:ss");
                orderModel.setPlaceOrderTime(simpleDateFormat.format(new Date()));
                if(OrderModelDao.queryAllHangingOrder() == null) {
                    orderModel.setId(1);
                }else if(OrderModelDao.queryAllHangingOrder().size() >0 ){
                    List<OrderModel> list = OrderModelDao.queryAllHangingOrder();
                    orderModel.setId(list.get(list.size()-1).getId()+1);
                }else if(OrderModelDao.queryAllHangingOrder().size() == 0){
                    orderModel.setId(1);
                }
                orderModel.setAmountReceivable(actualMoney);
                orderModel.setName("测试");
                orderModel.setStatus(3);
                orderModel.setGoodList(goodLists);
                OrderModelDao.insertModel(orderModel);

                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.add(R.id.fl_container_right,OrderGetFragment.newInstance());
                fragmentTransaction.commitAllowingStateLoss();
            }else if (i == R.id.btn_settle) {//结账
                tvClear.setVisibility(View.GONE);
                orderModel = new OrderModel();
                List<GoodActModel> goodActModels = new ArrayList<>();
                goodActModels.addAll(goodLists);
                orderModel.setGoodList(goodActModels);
                SimpleDateFormat simpleDateFormat =new SimpleDateFormat("HH:mm:ss");
                orderModel.setPlaceOrderTime(simpleDateFormat.format(new Date()));
                if(OrderModelDao.queryAllOrder() == null) {
                    orderModel.setId(1);
                }else if(OrderModelDao.queryAllOrder().size() >0 ){
                    List<OrderModel> list = OrderModelDao.queryAllHangingOrder();
                    orderModel.setId(list.get(list.size()-1).getId()+1);
                }else if(OrderModelDao.queryAllOrder().size() == 0){
                    orderModel.setId(1);
                }
                orderModel.setAmountReceivable(actualMoney);
                orderModel.setName("测试");
                orderModel.setStatus(1);
                orderModel.setGoodList(goodLists);
                activity.changeRightFragment(PayFragment.newInstance(orderModel));
            }else if(i == R.id.fl_get_order){//取单
                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fl_container_right,OrderGetFragment.getInstance());
                fragmentTransaction.commitAllowingStateLoss();
            }else if(i == R.id.tv_add_good){//点菜
                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fl_container_right,ChooseGoodFragment.getInstance());
                fragmentTransaction.commitAllowingStateLoss();
                tvAddGood.setVisibility(View.GONE);
                tvHangOrder.setVisibility(View.VISIBLE);
            }
    }



    public void addShopCart(GoodActModel goodActModel) {
            tvGuide.setVisibility(View.GONE);
            boolean hasGood = false;
            for (int i = 0; i < goodLists.size(); i++) {
                GoodActModel good = goodLists.get(i);
                if (goodActModel.getId() == good.getId()) {
                    if (goodActModel.getHasNorm() == 1) {
                        if (goodActModel.getNormsId().equals(good.getNormsId())) {
                            hasGood = true;
                            good.setCarNum(good.getCarNum() + 1);
                        }
                    } else {
                        hasGood = true;
                        good.setCarNum(good.getCarNum() + 1);
                    }
                }
            }
            if (!hasGood) {
                GoodActModel actModel = new GoodActModel();
                actModel.setId(goodActModel.getId());
                actModel.setName(goodActModel.getName());
                actModel.setNormsId(goodActModel.getNormsId());
                actModel.setSelectNorms(goodActModel.getSelectNorms());
                actModel.setPrice(goodActModel.getPrice());
                actModel.setCarNum(1);
                actModel.setHasNorm(goodActModel.getHasNorm());
                goodLists.add(actModel);
            }
            updateAmountPrice();
            orderAdapter.notifyDataSetChanged();
    }

    public void setRemarks(String remarks,String remarksId){
        this.remarksId = remarksId;
        tvRemarks.setText(remarks);
        FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
        fragmentTransaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
        fragmentTransaction.remove(OrderRemarkFragment.getInstance());
        fragmentTransaction.commitAllowingStateLoss();
    }


    private void updateAmountPrice(){
        actualMoney = 0;
        totalMoney = 0;
        totalNumber = 0;
        freeMoney = 0;
        for (int i = 0; i < goodLists.size(); i++) {
            GoodActModel goodActModel = goodLists.get(i);
            totalMoney += goodLists.get(i).getPrice()*goodLists.get(i).getCarNum();
            if(goodActModel.getStatus() !=2) {
                if (goodActModel.getDiscount() > 0) {
                    actualMoney += goodActModel.getDiscount()/10f * goodActModel.getPrice()*goodLists.get(i).getCarNum();
                    freeMoney += (1-goodActModel.getDiscount()/10f) * goodActModel.getPrice()*goodLists.get(i).getCarNum();
                } else if (goodActModel.getFree() == 0) {
                    actualMoney += goodActModel.getPrice()*goodLists.get(i).getCarNum();
                }else if(goodActModel.getFree() == 1){
                    freeMoney += goodActModel.getPrice()*goodLists.get(i).getCarNum();
                }
                totalNumber++;
            }
        }
        tvMoneyLast.setText("￥" + SDNumberUtil.doubleTrans(actualMoney));
        tvMoneyTrue.setText("￥" + SDNumberUtil.doubleTrans(totalMoney));
        tvMoneyMinus.setText("优惠金额：￥" + SDNumberUtil.doubleTrans(freeMoney));
        tvTotalNum.setText("总计:" + totalNumber);
        orderAdapter.notifyDataSetChanged();

    }


}
